<?php

namespace app\api\controller;

use app\api\model\Integral;
use app\api\model\SystemUser;
use app\api\model\Userdeposit;
use app\api\model\Usermoney;
use app\api\model\UserShop;
use app\common\controller\Api;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Db;
use think\Model;
use think\Validate;
use app\api\model\Config as ConfigModel;
use app\api\model\User as UserModel;
use app\api\model\GoodsComment as GoodsCommentModel;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = [
        'goodscomments',
        'Modelsdel',
        'Usermodels',
        'Modelslist',
        'downloadbill',
        'shopUser'
    ];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }
    /**
     * 安装店注册
     */
    public function shopUser()
    {
         $uid = $this->auth->id;
         $user = Db::name('user')->where('id',$uid)->find();

         if (!$user) $this->success('没有查询到此用户,请从新登录下','',401);
         if ($user['is_status'] == 1) $this->success('无法登录,请联系管理员','',400);
        $params    = $this->request->param();
        $user_shop = Db::name('user_shop')->where('uid',$uid)->find();

        if ($user_shop)
        {
            $this->success('您已申请无需重复操作','',400);
        }

         if (!$params['code']) $this->success('请输入验证码','',400);

         if (!$params['type']) $this->success('请先勾选用户协议','',400);

         $rule = [
             'shop_name' => 'require|max:100;',
             'address'   => 'require',
             'name'      => 'require|max:25',
             'phone'     => 'require|regex:1[3-8]{1}[0-9]{9}',
             'service_type'   => 'require',
             'service_models' => 'require'
         ];

         $msg = [
             'shop_name.require'    => '店铺名称不能为空',
             'shop_name.max'    => '店铺名最多100字',
             'address.require'  => '店铺地址必填',
             'name.require'     => '联系人姓名不能为空',
             'phone.require'    => '联系人电话不能为空',
             'phone.regex'      => '联系人电话格式不对',
             'service_type.regex'   => '服务类型不能为空',
             'service_models.regex' => '服务类型不能为空',
         ];
         $sms = Sms::check($params['phone'], $params['code'], 'register');

         if (!$sms) $this->success('验证码错误','',400);

         $Validate = new Validate($rule,$msg);
         if (!$Validate->check($params))
         {
             $this->success($Validate->getError(),'',400);
         }

         $params['uid']  = $uid;
         $params['user_name']  = $user['nickname'];
         $params['create_time'] = time();
         $params['status'] = 0;
         unset($params['code']);
         unset($params['type']);
         if (empty($params['businessimage']))
         {
             $this->success('请上传营业执照','',400);
         }else{

             $FramecarApi = new \app\api\controller\Framecar();
             $businessimage = $FramecarApi->yyLicense($params['businessimage']);

             if ($businessimage['status'] == false)
             {
                 $this->success('营业执照审核失败请从新上传', '', 400);
             }
         }

         $res = Db::name('user_shop')->insert($params);
         if ($res)
         {
             Db::name('user')->where('id',$uid)->setField('condition',1);
             $this->success('已提交审核',$res,200);
         }else{
             $this->success('提交失败','',400);
         }
    }
    /**
     * 代理商注册
     */
    public function userAgent()
    {
        $uid = $this->auth->id;
        $user = Db::name('user')->where('id',$uid)->find();
        if (!$user) $this->success('没有查询到此用户,请从新登录下','',401);
        if ($user['condition'] == 1) $this->success('您已申请店铺,重复操作','',400);
        $params = $this->request->param();
        if (!$params['type']) $this->success('请先勾选用户协议','',400);
        if (!$params['code']) $this->success('请填写验证码','',400);

        $user_shop = Db::name('user_agent')->where('uid',$uid)->find();
        if ($user_shop['condition'] != 0)
        {
            if ($user_shop == 1)
            {
                $this->success('您已申请安装店,无法再次申请','',400);
            }
            if ($user_shop == 2)
            {
                $this->success('您已申请代理,无法重复申请','',400);
            }
        }

        $rule = [
            'platfrom_id' => 'require',
            'online_shop' => 'require',
            'shopkeeper' => 'require',
            'phone' => 'require|regex:1[3-8]{1}[0-9]{9}',
        ];
        $msg = [
            'shop_name.require'     => '店铺名称不能为空',
            'shop_name.max'         => '店铺名最多100字',
            'address.require'       => '店铺地址必填',
            'phone.require'         => '联系人电话不能为空',
            'phone.regex'           => '联系人电话格式不对',
            'service_type.regex'    => '服务类型不能为空',
        ];
        $ret = Sms::check($params['phone'], $params['code'], 'register');

        if (empty($ret))
        {
            $this->success('验证码错误', '', 400);
        }
        $Validate = new Validate($rule,$msg);
        if (!$Validate->check($params))
        {
            $this->success($Validate->getError(),'',400);
        }

        if (empty($params['businessimage']))
        {
            $this->success('请上传营业执照','',400);
        }else{

            $FramecarApi = new \app\api\controller\Framecar();
            $businessimage = $FramecarApi->yyLicense($params['businessimage']);

            if ($businessimage['status'] == false)
            {
                $this->success('营业执照审核失败请从新上传', '', 400);
            }
        }

        $params['uid']         = $uid;
        $params['user_name']   = $user['nickname'];
        $params['create_time'] = time();
        $params['status'] = 0;
        unset($params['type']);
        unset($params['code']);
        $res = Db::name('user_agent')->insert($params);
        if ($res)
        {
            Db::name('user')->where('id',$uid)->setField('condition',2);
            $this->success('已提交审核',$res,200);
        }else{
            $this->success('提交失败','',400);
        }
    }
    /**
     * 反馈信息
     *
     */
    public function feedback()
    {
        $uid = $this->auth->id;
        $content = $this->request->param('content');
        $UserModel = new UserModel();
        $userInfo = $UserModel->getUser($uid);
        if (!$userInfo) $this->success('用户信息不存在','',400);

        $UserModel->getFeedback($userInfo,$content);

        $this->success('反馈成功','',200);
    }
    /**
     * 签到信息
     */
    public function Usersign()
    {
        $uid = $this->auth->id;

        $UserModel = new UserModel();
        $user = $UserModel->getUser($uid); // 查询到用户信息

        if (!$user) $this->success('用户信息不存在请联系管理员','',400);

        $usercount = Db::name('sign')->where('user_id',$uid)->count();  // 总签到数

        $sign_time = strtotime(date("Y-m-d"));

        if ($user['singtime'] == $sign_time)
        {
            $sign = '已签到';
        }else{
            $sign = '未签到';
        }

        $data = [
            'id'       => $user['id'],
            'nickname' => $user['nickname'],
            'avatar'   => $user['avatar'],
            'score'    => $user['score'],
            'is_sign'  => $user['is_sign'],
            'count'    => $usercount
        ];

        $this->success($sign,$data,200);
    }
    /**
     * 签到
     */
    public function Singin()
    {
        $uid = $this->auth->id;
        $UserModel = new UserModel();
        $user = $UserModel->getUserInfo($uid); // 查询用户是否存在

        if (!$user['data']) $this->success('用户信息不存在请联系管理员','',400);
        if ($user['data']['status']  == 1) $this->success('目前无法操作请联系管理员','',400);

        $time = strtotime(date('Y-m-d'));

        if ($user['data']['singtime'] == $time)
        {
            $this->success('您今天已签到','',400);
        }

        if ($user['data']['is_sign'] >= 7)
        {
            $is_sign = 1;
        }else{
            $is_sign = $user['data']['is_sign'] + 1;
        }

        $integral = ConfigModel::getSing();
        $userupdata = [
            'singtime' => $time,
            'is_sign'  => $is_sign,
        ];

        Db::startTrans();
        try {
            $UserModel->signAdd($uid, $time, $integral); //插入签到记录
            if ($user['is_vip'] == 2 || $user['is_vip'] == 3)
            {
                $user_money = [
                    'uid'   => $uid,
                    'money' => $integral,
                    'type'  => 'sign',
                    'create_time'  => time(),
                    'is_type'      => 1,
                ];
                Db::name('user_money')->insertGetId($user_money); //添加余额记录

                $userupdata['score'] = bcadd($user['data']['money'], $integral);
            }else{
                $integral_money = [
                    'uid'          => $uid,
                    'integral'     => $integral,
                    'type'         => '1',
                    'create_time'  => time(),
                    'is_type'      => 1,
                ];
                Db::name('integral')->insertGetId($integral_money); //添加余额记录
                $userupdata['score'] = bcadd($user['data']['score'], $integral);
            }

            $UserModel->updateUser($uid, $userupdata);

            Db::commit();
        }catch(\Exception $e){
            echo "<p>Exception: " . $e->getMessage() . "</p>";
            Db::rollback();
            $this->success('签到失败','',400);
        }
        $this->success('签到成功','',200);
    }
    /**
     * 修改用户信息
     */
    public function Userprofile()
    {
        $uid = $this->auth->id;
        $nickname = $this->request->param('nickname');
        $avater   = $this->request->param('avatar');
        $base = \think\Request::instance()->domain();
        $user = new UserModel();
        $userinfo = $user->getUser($uid);
        if (!$userinfo) $this->success('用户信息不存在','',400);
        if ($nickname)
        {
            $data = ['nickname' => $nickname];
        }
        if ($avater)
        {
            $data = ['avatar' => $base.'/'.$avater];
        }
        $userinfo = $user->updateUser($uid,$data);
        if ($userinfo)
        {
            $this->success('修改成功','',200);
        }else{
            $this->success('修改失败','',400);
        }
    }
    /**
     * 充值接口
     */
    public function Userprice()
    {
        $uid = $this->auth->id;
        $ConfigModel = new ConfigModel();
        if (!$uid) $this->success('获取成功','',200);
        $data = $ConfigModel->Getuserprice($uid);
        $this->success('获取成功', $data, 200);
    }
    /**
     * 安装店通知
     */
    public function systemUser()
    {
        $uid = $this->auth->id;
        $id = $this->request->post('id');
        if ($id)
        {
            $systemData = SystemUser::getSystemUserId($uid);
            if ($systemData)
            {
                $this->success('获取成功', $systemData, 200);
            }

        }
        $data = SystemUser::getSystemUser($uid);
        if ($data)
        {
            $this->success('获取成功',$data,200);
        }else{
            $this->success('没有消息通知', '', 200);
        }
    }
    /**
     * 订单通知
     */
    public function systemorder()
    {
        $uid = $this->auth->id;
        $data = SystemUser::getSystemOrder($uid);
        if ($data)
        {
            $this->success('获取成功', $data, 200);
        }else{
            $this->success('目前没有消息', '', 200);
        }
    }
    /**
     * 商品评论列表
     */
    public function goodscomments()
    {
        $uid = $this->auth->id;
        $id = $this->request->param('id');
        $data = GoodsCommentModel::commentslist($id,$uid,$type = 'goods');
        if ($data)
        {
            $this->success('获取成功',$data,200);
        }else{
            $this->success('暂无评论','',200);
        }
    }
    /**
     * 积分明细
     */
    public function userintegral()
    {
        $uid = $this->auth->id;
        $user_integral = Integral::where('uid',$uid)->order('create_time desc')->select();
        if ($user_integral)
        {
            $this->success('获取成功',$user_integral,200);
        }else{
            $this->success('目前没有积分','',200);
        }
    }
    /**
     * 用户提现
     */
    public function userrawal()
    {
        $uid = $this->auth->id;
        $integral  = $this->request->post('integral');
        $phone     = $this->request->post('phone');
        $UserModel = new UserModel();
        $user      = $UserModel->getUserInfo($uid);

        if ($user['is_vip'] == 2 || $user['is_vip'] == 3)
        {
            $this->success('目前无法提现','',400);
        }

        if ($user['data']['score'] < $integral)
        {
            $this->success('已超出现有积分','',400);
        }

        try {
            $scaleprice = ConfigModel::interPrice();
            $scaleprice = empty($scaleprice) ? 1 : $scaleprice;

            $money = bcmul($integral, $scaleprice, 2);
            $time = time();
            $Userdeposit = new Userdeposit;
            $Userdeposit->uid         = $uid;
            $Userdeposit->integral    = $integral;
            $Userdeposit->price       = $money;
            $Userdeposit->phone       = $phone;
            $Userdeposit->create_time = $time;
            $Userdeposit->save();

            if ($Userdeposit->id)
            {
                $balance_price = bcsub($user['data']['score'], $integral, 2);
                $UserModel->where('id',$uid)->setField('score', $balance_price);
                $IntegralModel = new Integral();

                $IntegralModel->uid         = $uid;
                $IntegralModel->integral    = $integral;
                $IntegralModel->create_time = $time;
                $IntegralModel->type        = 7;
                $IntegralModel->is_type     = 2;
                $IntegralModel->save();
                Db::commit();
                $response = true;
            }else{
                $response = false;
            }

        }catch (\Exception $e){
            Db::rollback();
            var_dump($e->getMessage());
            $response = false;
        }
        if ($response)
        {
            $this->success('已提交审核','',200);
        }else{
            $this->success('提交失败','',400);
        }
    }
    /**
     * 用户详情
     */
    public function userInfo()
    {
        $uid = $this->auth->id;
        $UserModel = new UserModel();
        $userInfo = $UserModel->getUserInfo($uid);

        if ($userInfo)
        {
            $userInfo['data']['start_time'] = '';
            $userInfo['data']['end_time']   = '';
            if ($userInfo['is_vip'] == 1)
            {
                $usershop = UserShop::get(['uid' => $uid]);
                $userInfo['data']['start_time'] = $usershop['start_time'];
                $userInfo['data']['end_time']   = $usershop['end_time'];
            }
            $this->success('获取成功', $userInfo, 200);
        }else{
            $this->success('获取失败', '', 401);
        }
    }
    /**
     *  充值余额明细
     */
    public function moneylist()
    {
        $uid = $this->auth->id;
        $list = Usermoney::where('uid',$uid)->order('create_time desc')->select();
        if ($list)
        {
            $this->success('获取成功', $list, 200);
        }else{
            $this->success('暂无数据', [], 200);
        }
    }
    /**
     * 下载账单
     */
    public function downloadbill()
    {

        $uid = $this->auth->id;
        $uid = 28;
        $user = UserModel::get($uid);

        if (empty($user))
            $this->success('用户信息不存在','',400);
        $usermoney = Usermoney::where('uid',$user['id'])->select();

        if (empty($usermoney))
            $this->success('暂无交易记录','',400);

        foreach ($usermoney as $key => &$val)
        {
            switch ($val['type'])
            {
                case 'topup':
                    $type = '充值';
                    break;
                case 'sign':
                    $type = '签到';
                    break;
                case 'share':
                    $type = '分享';
                    break;
                case 'commission':
                    $type = '佣金';
                    break;
                case 'consumption':
                    $type = '消费';
                    break;
                case 'rewview':
                    $type = '评论';
                    break;
                case 'refund':
                    $type = '退款';
                    break;
            }
            $val['type'] = $type;
            $val['money'] = $val['is_type'] == 1 ? $val['money'] : $val['money'];
            $val['create_time'] = date('Y-m-d H:i:s',$val['create_time']);
        }
        exportExcel($usermoney);
    }
}
